<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;
use aphp\core\Tool;

class Doc
{
    use Jump;

    // 检测权限
    protected function _check_level(int $level = 1)
    {
        if ((int)session('user.level') < $level) {
            $this->error('权限不足', 403);
        }
    }

    // 列表
    public function index()
    {
        return view();
    }

    // 添加
    public function add(array $req)
    {
        $this->_check_level(2);
        if ($this->isPost()) {
            $r = pdo()->trans(function () use ($req) {
                model('doc')->save($req);
            });
            $this->_jump(['添加成功', '添加失败'], $r, 'index/index');
        }
        return view();
    }

    // 修改
    public function edit(int $id, array $req)
    {
        $this->_check_level(2);
        $model = model('doc')->find($id);
        if (!$model) {
            $this->error('记录不存在');
        }
        if ($this->isPost()) {
            $r = pdo()->trans(function () use ($model, $req) {
                $model->save($req);
            });
            $this->_jump(['修改成功', '修改失败'], $r, 'index/index');
        }
        return view()->with(['vo' => $model->toArray()]);
    }

    // 删除
    public function del(int $id)
    {
        $this->_check_level(2);
        if ($this->isAjax()) {
            $model = model('doc')->find($id);
            if (!$model) {
                $this->error('记录不存在');
            }
            $r = $model->del();
            $this->_jump(['删除成功', '删除失败'], $r, 'index/index');
        }
        $this->error('非法操作');
    }

    // 下载
    public function down(int $id)
    {
        $list = db('doc_data')->field('id,doc_id,name,markdown')->where('doc_id', $id)->where('status=1')->order('sort ASC,id ASC')->select();
        $doc_name = db('doc')->where('id', $id)->value('name');
        $path = ROOT_PATH.'/public/doc/'.$doc_name;
        if (is_dir($path)) {
            Tool::dir_delete($path);
        } else {
            Tool::dir_init($path, 0777);
        }
        foreach ($list as $k => $vo) {
            $k ++;
            $k = str_pad(strval($k), 2, '0', STR_PAD_LEFT);
            file_put_contents($path.'/_'.$k.'_'.$vo['name'].'.md', $vo['markdown']);
        }
        $zipFile = $path . '.zip';
        if (file_exists($zipFile)) {
            unlink($zipFile);
        }
        $zip = new \PharData($zipFile);
        $zip->buildFromDirectory($path, '/\.md$/');
        if (!is_file($zipFile)) {
            $this->error('备份文件不存在');
        }
        if (ob_get_length() !== false) @ob_end_clean();
        header('Content-Type: application/zip');
        header('Content-Disposition:attachment;filename=doc_' . $doc_name . '.zip');
        header('Content-Length:' . filesize($zipFile));
        @readfile($zipFile);
        @unlink($zipFile);
        exit;
    }
}